package com.zmn.oms.third.taobao.msghandler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.ltsopensource.core.domain.Job;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageStatus;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.lts.interfaces.task.TaskManager;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.TaskConsts;
import com.zmn.oms.model.dto.order.proxy.*;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.third.base.constant.OrderReasonConsts;
import com.zmn.oms.third.taobao.TaobaoTmcConstants;
import com.zmn.oms.third.taobao.TaobaoTmcUtil;
import com.zmn.oms.third.taobao.dto.TmcOrderOtherDTO;
import com.zmn.oms.zmn.business.interfaces.proxy.ProxyOrderBService;
import com.zmn.oms.zmn.business.interfaces.tmall.TmallOrderBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 类描述：订单消息处理器
 *
 * @author yule
 * @date 2019/10/14 17:35
 */
@Component("orderOtherTmcMsgHandler")
public class OrderOtherTmcMsgHandler extends TmcMsgHandlerBase {
    private static final Logger logger = LoggerFactory.getLogger(OrderOtherTmcMsgHandler.class);

    @Autowired
    private ProxyOrderBService proxyOrderBService;
    @Autowired
    private TmallOrderBService tmallOrderBService;
    @Autowired
    private TaskManager taskManager;

    /**
     * 处理订单消息
     *
     * @param message
     * @param status
     */
    @Override
    public void procMsg(Message message, MessageStatus status) {
        try {
            logger.info("【{}】消息处理 message:[{}], status:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, message.toString(), status.toString());
            TmcOrderOtherDTO tmcOrderOtherDTO = TaobaoTmcUtil.parseMessageContent(message.getContent(), TmcOrderOtherDTO.class);
            String action = tmcOrderOtherDTO.getAction();
            // 天猫天猫勤鸽店（无忧购）订单消息
            procMsg4TmallQG(action, tmcOrderOtherDTO, message);
        } catch (Exception e) {
            logger.info("【{}-消息-订单】消息处理失败，触发消息重发！ErrorMsg:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, e.getMessage());
            logger.error(e.getMessage(), e);
            status.fail(); // 消息处理失败回滚，服务端需要重发
        }
    }

    /**
     * 处理天猫勤鸽店（无忧购）订单消息
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void procMsg4TmallQG(String action, TmcOrderOtherDTO tmcOrderDTO, Message message) throws Exception {
        /* 分析推送过来的订单的节点变化*
        /* 当订单信息（节点）发生变化时，淘宝会将最新订单信息推送过来（包括（action）来区分出该订单消息的业务类型  */

        // 修改预约时间/确定时间挂起
        if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_UPDATA_DUTYTIME, action)) {
            if (Objects.nonNull(tmcOrderDTO.getReasonCode())) {//如果不为空
                //挂起（确定下次上门时间）记录挂起日志
                tmcOrderDTO.setStatusFlag(GlobalConsts.YES);
                orderHangUp(tmcOrderDTO, message);
            }
            //修改预约时间（确定挂起和改约都需要进行改约）
            updateOrderWorkDutyTime(tmcOrderDTO, message);
        }
        // 勤鸽工人签到成功
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_SIGN_IN, action)) {
            tmcOrderDTO.setStatusFlag(GlobalConsts.YES);
            if (StringUtil.isNotBlank(tmcOrderDTO.getValidateFailReason())) {
                tmcOrderDTO.setStatusFlag(GlobalConsts.NO);
            }
            signIn(tmcOrderDTO, message);
        }

        //region 废弃 后期需要删除
        // 天猫签到失败top已经废弃,用上面validateFailReason字段判断是否签到失败，签到失败不堵塞核销
        // 勤鸽工人签到失败（连续三次失败）
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_SIGN_IN_FAILED, action)) {
            tmcOrderDTO.setStatusFlag(GlobalConsts.NO);
            signIn(tmcOrderDTO, message);
        }
        //endregion

        // 勤鸽工人接单（啄木鸟领单）
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_MASTER_TAKE, action)) {
            //工人接单-->变更工单状态到已领单
            orderMasterTake(tmcOrderDTO, message);
        }
        // 勤鸽工人放弃工单（派单撤回）
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_DISTRIBUTE_BACK, action)) {
            //工人弃单-->更改为派单撤回
            orderDistributeBack(tmcOrderDTO, message);
        }
        // 核销（勤鸽工单完成）
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_COMPLETE, action)) {
            tmcOrderDTO.setStatusFlag(GlobalConsts.YES);
            orderVerification(tmcOrderDTO, message);
        }
        // 工单取消
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_CANCEL, action)) {
            cancelOrder(tmcOrderDTO, message);
        }
        //挂起（不确定下次上门时间）
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_SUSPEND, action)) {
            tmcOrderDTO.setStatusFlag(GlobalConsts.NO);
            orderHangUp(tmcOrderDTO, message);
        }
        //预约失败
        else if (Objects.equals(TaobaoTmcConstants.ORDER_TASK_RESERVE_FAILED, action)) {
            orderReserveFailed(tmcOrderDTO, message);
        }
        // 其他状态不做处理
        else {
            logger.info("【{}-消息-订单】非订单操作消息数据（已忽略） action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL_QG, action);
        }
    }

    /**
     * 取消订单
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void cancelOrder(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);
        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理取消订单消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }
        if (!Objects.equals(OrderStatusConsts.WORK_RESULT_DOING, orderWork.getResultStatus())) {
            logger.info("【{}-消息-订单】非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
            return;
        }
        logger.info("【{}-消息-订单】顾客取消订单消息数据 Action:[{}]",
                TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());

        // 取消订单
        try {
            CancelOrderDTO cancelOrderDTO = new CancelOrderDTO();
            cancelOrderDTO.setChannelId(orderWork.getChannelId());
            cancelOrderDTO.setOrderId(orderWork.getOrderId());
            cancelOrderDTO.setRemark("顾客取消订单");
            cancelOrderDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            proxyOrderBService.cancelOrder(cancelOrderDTO);
        } catch (OmsBaseException e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 添加回复预约时间任务
     *
     * @param outerId
     * @param buyerExpectDate
     */
    private void addReplyUpdateDutyTimeJob(String outerId, String buyerExpectDate) {
        // 20秒钟后，更新天猫同步的预约时间
        Job job = new Job();
        job.setTaskId(TaskConsts.TASK_ID_TMALL_SYNC_DUTYTIME_JOB + ":" + outerId);
        job.setParam("outerId", outerId);
        job.setParam("buyerExpectDate", buyerExpectDate);
        job.setParam(TaskManager.SHARD_FIELD, TaskConsts.TASK_ID_TMALL_SYNC_DUTYTIME_JOB);
        Date date = DateUtil.addSecond(DateUtil.getNow(), 20);
        taskManager.submitTask(job, -1, DateUtil.dateFormatToString(date, DateUtil.FORMAT_DEFAULT));
    }

    /**
     * 修改预约时间
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void updateOrderWorkDutyTime(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);
        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理修改预约时间消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);

            if (TaobaoTmcConstants.ORDER_TASK_SOURCE.equals(tmcOrderDTO.getSource()) && !Objects.isNull(tmcOrderDTO.getBuyerExpectDate())) {
                logger.info("【{}-消息-订单】开始定时同步用户期望时间！ OuterId:[{}] --buyerExpectDate:[{}]",
                        TaobaoTmcConstants.NAME_TMALL, outerId, tmcOrderDTO.getBuyerExpectDate());
                addReplyUpdateDutyTimeJob(outerId, tmcOrderDTO.getBuyerExpectDate());
            }
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】 OuterId:[{}]处理修改预约时间非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId, tmcOrderDTO.getAction());
            return;
        }

        //消费者操作用户期望时间
        if (TaobaoTmcConstants.ORDER_TASK_SOURCE.equals(tmcOrderDTO.getSource())) {
            this.updateExpectDate(tmcOrderDTO, message);
            return;
        }

        if (StringUtil.isBlank(tmcOrderDTO.getReserveTimeStart())) {
            logger.info("【{}-消息-订单】 OuterId:[{}]处理修改预约时间失败-天猫预约时间数据缺失", TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        // 保存新的预约时间
        try {
            OrderDutyTimeDTO dutyTimeDTO = new OrderDutyTimeDTO();
            dutyTimeDTO.setWorkId(orderWork.getWorkId());
            dutyTimeDTO.setOrderId(orderWork.getOrderId());
            dutyTimeDTO.setChannelId(orderWork.getChannelId());
            dutyTimeDTO.setDutyTime(DateUtil.parse(tmcOrderDTO.getReserveTimeStart()));
            dutyTimeDTO.setChannelId(orderWork.getChannelId());
            dutyTimeDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            dutyTimeDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            dutyTimeDTO.setMasterId(orderWork.getMasterId());
            dutyTimeDTO.setReserveTimeStart(StringUtil.isNotBlank(tmcOrderDTO.getReserveTimeStart()) ? DateUtil.parse(tmcOrderDTO.getReserveTimeStart()) : null);
            dutyTimeDTO.setReserveTimeEnd(StringUtil.isNotBlank(tmcOrderDTO.getReserveTimeEnd()) ? DateUtil.parse(tmcOrderDTO.getReserveTimeEnd()) : null);
            tmallOrderBService.updateOrderWorkDutyTime(dutyTimeDTO);
        } catch (OmsBaseException e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略修改预约操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 签到
     * 工人接单-->变更工单状态到已领单
     * @param tmcOrderDTO
     * @param message
     */
    private void signIn(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);
        SignInDTO signInDTO = new SignInDTO();

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理工人签到消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】OuterId:[{}]处理工人签到非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId, tmcOrderDTO.getAction());
            return;
        }

        // 处理签到失败原因
        String signInFailReason = tmcOrderDTO.getValidateFailReason();
        if (StringUtil.isNotBlank(signInFailReason) && Objects.equals(tmcOrderDTO.getStatusFlag(), GlobalConsts.NO)) {
            try {
                StringBuilder bufferReason = new StringBuilder();
                JSONArray validateFailCodeArr = JSON.parseArray(signInFailReason);
                if (validateFailCodeArr.size() > 0) {
                    validateFailCodeArr.stream().forEach(item ->
                            bufferReason.append(OrderReasonConsts.getTmallValidateFailReason(item.toString())).append(";")
                    );
                }
                signInDTO.setSignInFailReasonName(bufferReason.toString());
                signInDTO.setSignInFailReason(signInFailReason);
            } catch (Exception e) {
                System.out.println("失败了哦");
                logger.error(e.getMessage(), e);
            }
        }

        try {
            signInDTO.setSignInStatus(tmcOrderDTO.getStatusFlag());
            signInDTO.setWorkId(orderWork.getWorkId());
            signInDTO.setOrderId(orderWork.getOrderId());
            signInDTO.setWorkcardId(tmcOrderDTO.getWorkcardId());
            signInDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            signInDTO.setChannelId(orderWork.getChannelId());
            signInDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            tmallOrderBService.signIn(signInDTO);
        } catch (Exception e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 勤鸽工人接单（啄木鸟领单）
     * 工人接单-->变更工单状态到已领单
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void orderMasterTake(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理工人接单失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】处理工人接单失败非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
            return;
        }

        if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_DISTRIBUTE)) {
            logger.info("【{}-消息-订单】处理工人接单失败工单不是派单状态，不能接单 Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
        }

        try {
            OrderMasterTakeDTO masterTakeDTO = new OrderMasterTakeDTO();
            masterTakeDTO.setMasterId(orderWork.getMasterId());
            masterTakeDTO.setOrderId(orderWork.getOrderId());
            masterTakeDTO.setWorkId(orderWork.getOrderId());
            masterTakeDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            masterTakeDTO.setChannelId(orderWork.getChannelId());
            masterTakeDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            tmallOrderBService.updateMasterTake(masterTakeDTO);
        } catch (OmsBaseException e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 勤鸽工人放弃工单（派单撤回）
     * 工人弃单-->更改为派单撤回
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void orderDistributeBack(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理工人放弃工单失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】处理工人放弃工单失败非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
            return;
        }

        StringBuilder reason = new StringBuilder();
        String reasonCodeName = OrderReasonConsts.getDistributeBackReasonCodeName(tmcOrderDTO.getReasonCode());
        if (StringUtil.isNotBlank(reasonCodeName)) {
            reason.append(reasonCodeName).append("；");
        }

        if (StringUtil.isNotBlank(tmcOrderDTO.getReasonDesc())) {
            reason.append("描述：").append(tmcOrderDTO.getReasonDesc());
        }

        try {
            DistributeBackDTO distributeBackDTO = new DistributeBackDTO();
            distributeBackDTO.setOperatorRemark(reason.toString());
            distributeBackDTO.setOrderId(orderWork.getOrderId());
            distributeBackDTO.setWorkId(orderWork.getWorkId());
            distributeBackDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            distributeBackDTO.setChannelId(orderWork.getChannelId());
            distributeBackDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            tmallOrderBService.updateDistributeBack(distributeBackDTO);
        } catch (OmsBaseException e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 核销
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void orderVerification(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理工核销工单失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }
        try {
            SignInDTO signInDTO = new SignInDTO();
            signInDTO.setOrderId(orderWork.getOrderId());
            signInDTO.setWorkId(orderWork.getWorkId());
            signInDTO.setWorkcardId(tmcOrderDTO.getWorkcardId());
            signInDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            signInDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            signInDTO.setChannelId(orderWork.getChannelId());
            signInDTO.setVerification(tmcOrderDTO.getStatusFlag());
            tmallOrderBService.updateVerificationStatus(signInDTO);
        } catch (Exception e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 挂起（确定下次上门时间）|| 挂起（不确定下次上门时间）
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void orderHangUp(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理挂起工单失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】处理挂起工单失败非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
            return;
        }

        StringBuilder reason = new StringBuilder();
        String reasonCodeName = OrderReasonConsts.getHangUpReasonCodeName(tmcOrderDTO.getReasonCode() == null ?
                StatusConsts.STATUS_ERROR : tmcOrderDTO.getReasonCode());

        if (Objects.equals(GlobalConsts.YES, tmcOrderDTO.getStatusFlag())) {
            reason.append("确定下次上门时间");
            reason.append(",预约开始时间：").append(tmcOrderDTO.getReserveTimeStart()).append("-");
            reason.append("预约结束时间：").append(tmcOrderDTO.getReserveTimeEnd()).append("；");
        } else {
            reason.append("不确定下次上门时间");
            if (StringUtil.isNotBlank(tmcOrderDTO.getGmtNextContact())) {
                reason.append(",下次联系时间:");
                reason.append(tmcOrderDTO.getGmtNextContact()).append("；");
            }
        }

        if (StringUtil.isNotBlank(reasonCodeName)) {
            reason.append("挂起原因：").append(reasonCodeName).append("；");
        }

        if (StringUtil.isNotBlank(tmcOrderDTO.getReasonDesc())) {
            reason.append("挂起描述：").append(tmcOrderDTO.getReasonDesc());
        }

        try {
            OrderHangUpDTO hangUpDTO = new OrderHangUpDTO();
            hangUpDTO.setOrderId(orderWork.getOrderId());
            hangUpDTO.setWorkId(orderWork.getWorkId());
            hangUpDTO.setOperatorRemark(reason.toString());
            hangUpDTO.setHangUpStatus(tmcOrderDTO.getStatusFlag());
            hangUpDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            hangUpDTO.setChannelId(orderWork.getChannelId());
            hangUpDTO.setMasterName(orderWork.getMasterName());
            hangUpDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            hangUpDTO.setNextContactTime(StringUtil.isNotBlank(tmcOrderDTO.getGmtNextContact()) ? DateUtil.parse(tmcOrderDTO.getGmtNextContact()) : null);
            tmallOrderBService.orderHangUp(hangUpDTO);
        } catch (Exception e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 勤鸽预约失败
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void orderReserveFailed(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理勤鸽预约失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        if (Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_COMPLETE) ||
                !Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_DOING)) {
            logger.info("【{}-消息-订单】处理勤鸽预约失败失败非新单消息数据（已忽略） Action:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, tmcOrderDTO.getAction());
            return;
        }

        Integer dutyFailCode = tmcOrderDTO.getReasonCode() == null ? GlobalConsts.NO : tmcOrderDTO.getReasonCode() + 1;
        try {
            OrderReserveFailedDTO reserveFailedDTO = new OrderReserveFailedDTO();
            reserveFailedDTO.setOrderId(orderWork.getOrderId());
            reserveFailedDTO.setWorkId(orderWork.getWorkId());
            reserveFailedDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            reserveFailedDTO.setChannelId(orderWork.getChannelId());
            reserveFailedDTO.setMasterName(orderWork.getMasterName());
            reserveFailedDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            reserveFailedDTO.setNextContactTime(StringUtil.isNotBlank(tmcOrderDTO.getGmtNextContact()) ? DateUtil.parse(tmcOrderDTO.getGmtNextContact()) : null);
            reserveFailedDTO.setDutyFailCode(dutyFailCode);
            reserveFailedDTO.setDutyStatus(OrderDutyConsts.DUTY_STATUS_FAIL);
            reserveFailedDTO.setReasonDesc(tmcOrderDTO.getReasonDesc());
            tmallOrderBService.orderReserveFailed(reserveFailedDTO);
        } catch (Exception e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 用户修改期望预约时间
     *
     * @param tmcOrderDTO
     * @param message
     */
    private void updateExpectDate(TmcOrderOtherDTO tmcOrderDTO, Message message) {
        String outerId = Long.toString(tmcOrderDTO.getWorkcardId());
        ZsOrderWorkVO orderWork = queryOrderByOuterId(outerId);

        if (orderWork == null) {
            logger.error("【{}-消息-订单】处理勤鸽预约失败消息时发生错误，系统中不存在对应的订单！ OuterId:[{}]",
                    TaobaoTmcConstants.NAME_TMALL, outerId);
            return;
        }

        StringBuilder reason = new StringBuilder();
        if (StringUtil.isNotBlank(tmcOrderDTO.getBuyerExpectDate())) {
            reason.append("用户修改期望预约时间->").append(tmcOrderDTO.getBuyerExpectDate()).append("；");
        }
        try {
            OrderDutyTimeDTO orderDutyTimeDTO = new OrderDutyTimeDTO();

            orderDutyTimeDTO.setOrderId(orderWork.getOrderId());
            orderDutyTimeDTO.setWorkId(orderWork.getWorkId());
            orderDutyTimeDTO.setPlat(orderWork.getPlatWork());
            orderDutyTimeDTO.setBizType(orderWork.getBizType());
            orderDutyTimeDTO.setOperatorRemark(reason.toString());
            orderDutyTimeDTO.setOuterData(JSON.toJSONString(tmcOrderDTO));
            orderDutyTimeDTO.setChannelId(orderWork.getChannelId());
            orderDutyTimeDTO.setMasterName(orderWork.getMasterName());
            orderDutyTimeDTO.setOuterId(tmcOrderDTO.getWorkcardId().toString());
            orderDutyTimeDTO.setBuyerExpectDate(StringUtil.isNotBlank(tmcOrderDTO.getBuyerExpectDate()) ? DateUtil.parse(tmcOrderDTO.getBuyerExpectDate()) : null);
            tmallOrderBService.updateExpectDate(orderDutyTimeDTO);
        } catch (Exception e) {
            // 捕获异常，不抛出方法外，不然会触发消息重发，
            // 此处处理失败，忽略取消操作
            logger.error(e.getMessage(), e);
        }

    }

}
